<?php

namespace app\order\logic;

use app\common\library\RedissLock;
use app\common\service\TiktokPackageApiService;
use think\facade\Db;
use app\order\logic\OrderServiceLogic;

class OrderDocumentServiceLogic
{
    /**
     * 创建面单队列消费
     * @param $data
     * @return void
     */
    public function orderShippingDocumentsQueueConsume($data)
    {
        //并发处理;
        $redis_lock = new RedissLock();
        $key        = 'orderShippingDocumentsQueueConsume:'.time();
        $lock       = $redis_lock::lock($key, $redis_lock::UNBLOCK, 400);
        if (!$lock) {
             return ['code'=>201,'msg'=>'数据并发了'];
        }
        htmlLog(['data'=>$data],OPERATE_LOG . date('Ym') . '/orderShippingDocumentsQueueConsume/' . date('Ymd') . '.txt');
        $return = (new TiktokPackageApiService())->createPackage($data);
        //对接买面单接口
        //下载pdf_url
        if ($return['code'] == 200){
            $log = [
                'batch_id'      =>$data['batch_id'],
                'order_id'      =>$data['order_id'],
                'shop_id'      =>$data['shop_id'],
                'status'        =>2,
                'msg'           =>'创建包ID成功',
                'package_id'    =>$return['data'],
                'created_time'  =>date("Y-m-d H:i:s", time()),
            ];

            Db::name('order_shipping_documents_log')->insert($log);
            Db::name('order')->where('order_id', $data['order_id'])->update([
                    'shipping_documents_status' => 2,
                    'package_id'                => $return['data'],
            ]);
            //获取创建PDF文件地址;
            $data['package_id'] = $return['data'];
          (new TiktokPackageApiService())->downDocUrl($data);
        } else {
            $log = [
                'batch_id'      =>$data['batch_id'],
                'order_id'      =>$data['order_id'],
                'shop_id'      =>$data['shop_id'],
                'status'        =>3,
                'msg'           =>'创建包ID失败',
                'package_id'    =>$return['data'],
                'created_time'  =>date("Y-m-d H:i:s", time()),
            ];
            Db::name('order_shipping_documents_log')->insert($log);
            Db::name('order')->where('order_id', $data['order_id'])->update([
                'shipping_documents_status' => 3,
                'package_id'                => $return['data'],
            ]);
        }
        $lock->unlock();
        return true;
    }
}
